<template>
  <div class="uploader-oss">
    <el-button type="primary" @click="uploadTips" v-show="showUpload"
      >点击上传{{ showTitle }}</el-button
    >
    <el-upload
      v-show="!showUpload"
      action
      :http-request="Upload"
      :before-upload="beforeAvatarUpload"
      :on-preview="handlePreview"
      :before-remove="beforeRemove"
      :on-remove="handleRemove"
      :on-success="handleSuccess"
      :on-exceed="handleExceed"
      :limit="limit"
      :file-list="fileList"
      ref="upload"
      accept=".doc,.doc,.xls,.xlsx,.csv,.ppt,.ppt,.pdf,.txt,.jpeg,.jpg,.png,.gif,.psd,.mp3,.wav,.wma,.avi,.mpeg,.wmv,.mp4,.mov,.flv,.zip,.rar,.tar,.7z "
    >
    </el-upload>

    <el-progress
      v-show="showProgress"
      :text-inside="true"
      :stroke-width="15"
      :percentage="progress"
    ></el-progress>
  </div>
</template>
<script>
import { client, getNowTime } from "@/assets/js/ali-oss"; //前面的ali-js文件内的两个封装函数
export default {
  name: "Upload",
  props: {
    limit: {
      type: Number,
      default: 1,
    },
    //组件唯一标识
    uploadId: {
      type: String,
      default() {
        return "uploadId";
      },
    },
    fileInfo: {
      default() {
        return {
          match_number: "match_number",
          company_title: "company_title",
        };
      },
      type: Object,
    },
    filePath: {
      default() {
        return "";
      },
      type: String,
    },
    fileList: {
      default() {
        return [];
      },
      type: Array,
    },
    showTitle: {
      default() {
        return "";
      },
      type: String,
    },
  },
  data() {
    return {
      showProgress: false, //进度条的显示
      progress: 0, //进度条数据
      showUpload: true,
    };
  },
  methods: {
    // 文件超出个数限制时的钩子
    handleExceed(files, fileList) {
      this.$message.warning(`每次只能上传 ${this.limit} 个文件`);
    },
    // 点击文件列表中已上传的文件时的钩子
    handlePreview(file) {},
    // 删除文件之前的钩子
    beforeRemove(file, fileList) {
      return this.$confirm(`确定移除 ${file.name}？`);
    },
    // 文件列表移除文件时的钩子
    handleRemove(file, fileList) {},
    // 文件上传成功时的钩子
    handleSuccess(response, file, fileList) {
      this.fileList = fileList;
    },
    //文件上传前的校验
    beforeAvatarUpload(file) {
      const whiteList = ["doc","doc","xls","xlsx","csv","ppt","ppt","pdf","txt","jpeg","jpg","png","gif","psd","mp3","wav","wma","avi","mpeg","wmv","mp4","mov","flv","zip","rar","tar","7z"];
      const fileSuffix = file.name.substring(file.name.lastIndexOf(".") + 1);
      if (whiteList.indexOf(fileSuffix) === -1) {
        this.$message.error('不支持此文件类型上传！');
        return false;
      }
    },
    uploadTips() {
      if (this.filePath) {
        this.$confirm("文件已上传，重新上传将覆盖源文件, 是否继续?", "提示", {
          confirmButtonText: "确定",
          cancelButtonText: "取消",
          type: "warning",
        })
          .then(() => {
            this.$refs["upload"].$refs["upload-inner"].handleClick(); //触发上传组件中的按钮点击事件
            return true;
          })
          .catch(() => {
            return false;
          });
      } else {
        this.$refs["upload"].$refs["upload-inner"].handleClick();
      }

    },
    // http-request属性来覆盖默认的上传行为（即action="url"），自定义上传的实现
    Upload(file) {
      const that = this;
      async function multipartUpload() {
        let temporary = file.file.name.lastIndexOf(".");
        let fileNameLength = file.file.name.length;
        let fileFormat = file.file.name.substring(
          temporary + 1,
          fileNameLength
        );
        let fileName =
          that.showTitle + "_" + getNowTime() + "." + fileFormat;
        let folderName = ""
        if(that.fileInfo.company_title){
          folderName =  `${that.fileInfo.match_number}_${that.fileInfo.company_title}`
        } else {
          folderName =  `${that.fileInfo.match_number}`
        }
        client()
          .multipartUpload(
            `${folderName}/${fileName}`,
            file.file,
            {
              progress: function (p) {
                //p进度条的值
                that.showProgress = true;
                that.progress = Math.floor(p * 100);
              },
            }
          )
          .then((result) => {
            //上传成功返回值，可针对项目需求写其他逻辑
            that.$refs.upload.clearFiles();
            that.$emit("uploadFile", {
              uploadId: that.uploadId,
              fileAddress: result.name,
            });
          })
          .catch((err) => {
            console.log("err:", err);
          });
      }
      multipartUpload();
    },
  },
};
</script>

<style scoped>
.uploader-oss {
  margin-top: 10px;
}
.uploader-oss >>>.el-progress-bar__inner{
  /* background: url('../assets/images/userCenter/progress_bg.png') repeat-x; */
}
</style>
